const { Modal, Form, Input, Button, Col, Row } = antd;



const NovelEd = ({ visible, onCancel, onOk, prompts }) => {
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);
  const [topicLoading, setTopicLoading] = useState(false);
  const [loadingDetail, setLoadingDetail] = useState(false);

  const [ideas, setIdeas] = useState([]);
  const [outlines, setOutlines] = useState([]);

  const [idea, setIdea] = useState({});
  const [outline, setOutline] = useState({});

  const [visibleSelIdea, setVisibleSelIdea] = useState(false);

  const [selType, setSelType] = useState('idea');

  const [ideapt, setIdeaPt] = useState({});
  const [outlinept, setOutlinePt] = useState({});
  const [plotpt, setPlotPt] = useState({});
  const [requirept, setRequirePt] = useState({});
  const [chpt, setChPt] = useState({});


  const fetchIdeaData = async () => {
      try {
          const ideas = await db.topic_ideas.toArray();
          prn(ideas)
          setIdeas(ideas);
      } catch (error) {
          console.error('从 topic_ideas 表加载数据时出错:', error);
      }
  };

  const loadOutlines = async () => {
      try {
          const data = await db.outlines.toArray();
          setOutlines(data);
      } catch (error) {
          console.error('Error loading outlines:', error);
      }
  };


  const loadGenPt = async () => {
      const data = await db.prompts.get(50)
      setIdeaPt(data)

      const odata = await db.prompts.get(51)
      setOutlinePt(odata)

      const pdata = await db.prompts.get(206)
      setPlotPt(pdata)

      const rdata = await db.prompts.get(196)
      setRequirePt(rdata)

      const cdata = await db.prompts.get(202)
      setChPt(cdata)
  }

    // 从 topic_ideas 表加载数据
    useEffect(() => {
        fetchIdeaData();
        loadOutlines()
        loadGenPt()
    }, []);


  const getEd = (id) => {
    let editor = window[id]
    return editor
  }

  const setEdVal = (id, val) => {
    let editor = getEd(id)
    if (editor){
      editor.setValue(val)
    }
  }

  const getEdVal = (id) => {
    let editor = getEd(id)
    if (editor){
      return editor.getValue()
    }else{
      return ''
    }
  }


  const handleOutlineClick = (item) => {
      console.log('Clicked item:', item);
      setOutline(item)
      setEdVal('editor_novel_gen', item.content)
  };

  const handleSelection = (selectedIdea) => {
      console.log('你选择的想法是:', selectedIdea);
      setIdea(selectedIdea)
      setEdVal('editor_novel_gen', selectedIdea.description)
  };

  const handleOk = () => {
    form.validateFields()
     .then(values => {
        onOk(values);
        form.resetFields();
      })
     .catch(info => {
        console.log('Validate Failed:', info);
      });
  };


  const updateDoc = ()=>{}


  const genTopicIdea = async () => {

    setTopicLoading(true);
    const props = {'output': 'JSON'}
    let ret = await $.genTopicIdea(ideapt.id, props)

    db.topic_ideas.bulkAdd(ret)
    setTopicLoading(false);

    prn(ret)

    fetchIdeaData()
  }

  const clearTopicIdea =async ()=>{
      await db.topic_ideas.clear()
      fetchIdeaData()
  }

  const genOutline = async () => {
    // prn(idea)
    prn(outlinept)
    setLoading(true);
    let ret = await $.genOutline(idea.id, outlinept.id)
    let cid = 'editor_novel_gen'
    setEdVal(cid, ret)

    db.outlines.add({content: ret})

    loadOutlines()
    setLoading(false);
  }

  const clearOutline =async ()=>{
      await db.outlines.clear()
      loadOutlines()
  }

  const genPlot = async () => {

    setLoadingDetail(true);

    // prn(outline)

    // let ret = $.genPlot(192, outline.id)

    let tpl = await $.get_gen_plot_prompt(plotpt.id, outline.id, requirept.id)
    
    prn('tpl', tpl)

    let cid = 'editor_novel_gen'
    setEdVal(cid, '')

    let llm = $.streamGlmApi
    await llm(tpl, (ret)=>{
      setEdVal(cid, getEdVal(cid) + ret)
    })    


    setLoadingDetail(false);
  }


  const write_chapter = async ()=>{
    prn('write_chapter')
    prn(chpt)

    let pt = chpt
    let props = {'ref': outline.content}
    let ret = await $.buildTplWithValues(pt, props)
    $.copyToClipboard(ret)
    prn(ret)
  }


  const copyEd = () => {
    let cid = 'editor_novel_gen'
    let c = getEdVal(cid)
    $.copyToClipboard(c)
  }


  const closeVisIdea = ()=>{
    setVisibleSelIdea(false)
  }

  const onRowClick = (r)=>{
    prn(r)
    prn(selType)

    // prn(ideapt)

    if(selType == 'idea' ){
      setIdeaPt(r)
    }else if(selType == 'outline' ){
      setOutlinePt(r)
    }else if(selType == 'plot' ){
      setPlotPt(r)
    }
    setVisibleSelIdea(false)
  }

  return (
    <Modal
      title="小说创作"
      width={1300}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="copy" onClick={copyEd}>copy</Button>,
        <Button key="topic_idea" onClick={genTopicIdea} loading={topicLoading}>生成选题思路</Button>,
        <Button key="outline" onClick={genOutline} loading={loading}>生成大纲</Button>,
        <Button key="detail_outline" onClick={genPlot} loading={loadingDetail}>生成情节</Button>,
        <Button key="write_chapter" onClick={write_chapter} >生成章节</Button>,
      ]}      
    >

    
    <Row>
      <Col span={8}>
        <Button key="setIdeaPt" onClick={()=>{ setSelType('idea'); setVisibleSelIdea(true)}}> 选择构思提示词</Button>,
        : {ideapt?.name}

        <br/> <br/>
        <Button key="setOutlinePt" onClick={()=>{ setSelType('outline'); setVisibleSelIdea(true)}}> 选择大纲提示词</Button>,
        : {outlinept?.name}

        <br/> <br/>
        <Button key="setPlotPt" onClick={()=>{ setSelType('plot'); setVisibleSelIdea(true)}}> 选择情节提示词</Button>,
        : {plotpt?.name}

        <br/> <br/>
        <Button key="setRequirePt" onClick={()=>{ setSelType('require'); setVisibleSelIdea(true)}}> 选择创作要求提示词</Button>,
        : {requirept?.name}

        <br/> <br/>
        <Button key="setChPt" onClick={()=>{ setSelType('require'); setVisibleSelIdea(true)}}> 选择正文提示词</Button>,
        : {chpt?.name}

        <br/> <br/>

        小说思路 
        <Button key="clearTopicIdea" onClick={clearTopicIdea}> 清空思路</Button>,
        <IdeaList onSelect={handleSelection} data={ideas} />

        小说大纲
        <Button key="clearOutline" onClick={clearOutline}> 清空大纲</Button>,
        <OutlineList onItemClick={handleOutlineClick} data={outlines} />
      </Col>
      <Col span={16}>
         <MonacoEditor 
          container_id='novel_gen'
          init_doc={''}
          updateDoc={updateDoc}
         />
      </Col>
    </Row>

    <Modal
      visible={visibleSelIdea}
      onOk={()=>setVisibleSelIdea(false)}
      onCancel={()=>setVisibleSelIdea(false)}
      width={999}
    >

      select idea

      <SelectIdea seltype={selType} prompts={prompts} onRowClick={onRowClick}/>

    </Modal>


    </Modal>
  );
};

